##### replication of figures 13 and 14

rm(list = ls())
library(tidyverse)
library(igraph)
library(ggraph)
library(data.table)

load(file="aggregated_nws.Rdata")

# replicate figure 14:
# Which groups are more likely to nominate which groups?

mymat <- instnw %>% as_adjacency_matrix(attr="weight") %>% as.matrix()
rowSums(mymat)
for(i in 1:dim(mymat)[1]){
  mymat[i,] <- mymat[i,]/rowSums(mymat)[i]
}
mymat
instmat <- mymat %>% as_tibble()
instmat$source <- names(instmat)

nomdatinst <- instmat %>% pivot_longer(cols=!source)

# Heatmap by type of institution
ggplot(nomdatinst, aes(name, source, fill= value)) + 
  geom_tile() + 
  geom_text(aes(fill = round(value, 2), label = round(value, 2))) +
  scale_fill_gradient(low = "white", high = "darkgrey") +
  theme(axis.text.x = element_text(angle = 45, hjust=1)) +
  xlab("target") +
  ggtitle("Fraction of expert nominations from source institution to target institution")

# Same for georegion:
mymat <- geonw %>% as_adjacency_matrix(attr="weight") %>% as.matrix()
rowSums(mymat)
for(i in 1:dim(mymat)[1]){
  mymat[i,] <- mymat[i,]/rowSums(mymat)[i]
}
mymat

geomat <- mymat %>% as_tibble()
geomat$source <- names(geomat)

nomdatgeo <- geomat %>% pivot_longer(cols=!source)

# replicate figure 13:

# Heatmap 
ggplot(nomdatgeo, aes(name, source, fill= value)) + 
  geom_tile() + 
  geom_text(aes(fill = round(value, 2), label = round(value, 2))) +
  scale_fill_gradient(low = "white", high = "darkgrey") +
  theme(axis.text.x = element_text(angle = 45, hjust=1)) +
  xlab("target") +
  ggtitle("Fraction of expert nominations from source region to target region")
